package com.webserver.controller;


import com.webserver.entity.User;
import com.webserver.http.HttpServletRequest;
import com.webserver.http.HttpServletResponse;
import org.apache.log4j.Logger;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class UserController {
    private static Logger logger = Logger.getLogger(UserController.class);

    private static File userDir;

    static {
        userDir = new File("users");
        if(!userDir.exists()){
            userDir.mkdirs();//创建文件夹
        }
    }

    public void showAllUser(HttpServletRequest request,HttpServletResponse response){
        List<User> userList = new ArrayList<>();
        File[] files = userDir.listFiles(f->f.getName().endsWith(".obj"));
        for (File f : files){
            try(
                    FileInputStream fis = new FileInputStream(f);
                    ObjectInputStream ois = new ObjectInputStream(fis);
            ) {
                User user = (User) ois.readObject();
                userList.add(user);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
        System.out.println("用户列表"+userList);

        response.setContentType("text/html");
        PrintWriter pw = response.getWriter();
            pw.println("<!DOCTYPE html>");
            pw.println("<html lang=\"en\">");
            pw.println("<head>");
            pw.println("<meta charset=\"UTF-8\">");
            pw.println("<title>用户列表</title>");
            pw.println("</head>");
            pw.println("<body>");
            pw.println("<center>");
            pw.println("<h1>用户列表</h1>");
            pw.println("<table border=\"1\" >");
            pw.println("<tbody align = \"center\">");
            pw.println("<tr>");
            pw.println("<td>用户名</td>");
            pw.println("<td>密码</td>");
            pw.println("<td>昵称</td>");
            pw.println("<td>年龄</td>");
            pw.println("</tr>");
            for(User user : userList){
                pw.println("<tr>");
                pw.println("<td>" + user.getUsername() + "</td>");
                pw.println("<td>" + user.getPassword() + "</td>");
                pw.println("<td>" + user.getNickname() + "</td>");
                pw.println("<td>" + user.getAge() + "</td>");
                pw.println("</tr>");
            }
            pw.println("</tbody>");
            pw.println("</table>");
            pw.println("</center>");
            pw.println("</body>");
            pw.println("</html>");
            System.out.println("页面已生成");

    }

    public void login(HttpServletRequest request, HttpServletResponse response){
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        //输入不规范
        if(username == null || password == null){
//            File file = new File(staticDir,"/myweb/login_info_error.html");
//            response.setContentFile(file);
            response.sendRedirect("/myweb/login_info_error.html");
            return;
        }

        File userFile = new File(userDir,username+".obj");

        if(userFile.exists()){//用户名正确
            try (
                    FileInputStream fis = new FileInputStream(userFile);
                    ObjectInputStream ois = new ObjectInputStream(fis);
            ){

                //读取注册的信息
                User obj = (User) ois.readObject();

                if(obj.getPassword().equals(password)){
                    //登录成功
//                    File file = new File(staticDir,"/myweb/login_success.html");
//                    response.setContentFile(file);
                    response.sendRedirect("/myweb/login_success.html");
                    return;
                }


            } catch (IOException | ClassNotFoundException e) {
                e.printStackTrace();
            }

        }

        //如果程序走到这里,情况1:用户名没有输入正确，文件不存在
        //              情况2:用户名对了，但是密码不对
//        File file = new File(staticDir,"/myweb/login_fail.html");
//        response.setContentFile(file);
        response.sendRedirect("/myweb/login_fail.html");



    }

    public void reg(HttpServletRequest request, HttpServletResponse response){
        logger.info("开始处理注册");//记录简单信息
//        logger.debug();
//        logger.error();

        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String nickname = request.getParameter("nickname");
        String ageStr = request.getParameter("age");
        logger.info(username+","+password+","+nickname+","+ageStr);

        if(username == null || password == null || nickname == null || ageStr == null || !ageStr.matches("[0-9]+")){
            response.sendRedirect("/myweb/reg_info_error.html");//重定向
            return;//直接结束方法
        }

        int age = Integer.parseInt(ageStr);
        System.out.println(username+","+password+","+nickname+","+age);

        User user = new User(username,password,nickname,age);
        File userFile = new File(userDir,username+".obj");

        //判断是否存在用户信息
        if(userFile.exists()){
            response.sendRedirect("/myweb/have_user.html");//重定向
            return;//直接结束方法
        }

        //写出用户obj文件，发送成功网页
        try(
                FileOutputStream fos = new FileOutputStream(userFile);
                ObjectOutputStream oos = new ObjectOutputStream(fos);
        ) {
            oos.writeObject(user);

            response.sendRedirect("/myweb/reg_success.html");//重定向

        } catch (IOException e) {
            e.printStackTrace();
            logger.error(e.getMessage(),e);
        }


    }
}
